<?php

namespace App\Models\Member;

use App\Models\BaseModel;
use App\Models\Member\User;
use App\Common\ValidateHandler;
use DB;

class Address extends BaseModel
{
    protected $fillable = [
        'id', 'user_id', 'accepter_name', 'accepter_phone', 'province_name', 'city_name',
        'id', 'district_name', 'detail_address', 'national_code',
        'created_at', 'updated_at'
    ];

    public function getAddressLists($user_id, $address_id = 0)
    {
        $address = $this->where('user_id', $user_id)->get()->toArray();

        return $this->successClient(['address' => $address, 'address_id' => $address_id], '获取地址列表成功!'); 
    }

    public function addressChange($info)
    {
        $id = $info['id'];
        $check = $this->validate($info);
        if (!$check['res']) {
            return $this->errorClient($check['res'], $check['info']); 
        }
        $isDefault = $info['isDefault'];
        $infoNew = $this->dataInfo($info);
        if ($id == 'new') {
            $data = $this->insertAddress($infoNew, $isDefault);
        } else {
            $infoNew['address_id'] = $info['address_id'];
            $data = $this->editAddress($infoNew, $isDefault);
        }
        return $data;
    }
    public function dataInfo($info)
    {
        $data = [];
        if ($info['id'] != 'new') {
            $data['id'] = $info['id'];
        }
        $data['user_id'] = $info['user_id'];
        $data['accepter_name'] = $info['accepter_name'];
        $data['accepter_phone'] = $info['accepter_phone'];
        $data['province_name'] = $info['province_name'];
        $data['city_name'] = $info['city_name'];
        $data['district_name'] = $info['district_name'];
        $data['detail_address'] = $info['detail_address'];
        $data['national_code'] = $info['national_code'];
        $data['created_at'] = date('Y-m-d H:i:s');
        return $data;
    }

    public function insertAddress($info, $isDefault = 0)
    {
        DB::beginTransaction();
        try {
            $back = $this->insertGetId($info);
            if (!$back) {
                return $this->errorClient($info, '地址插入失败!'); 
            }
            if ($isDefault == 1) {
                $user_up = User::where('id', $info['user_id'])->update(['address_id' => $back]);
                if (!$user_up) {
                    return $this->errorClient($info, '默认地址更新失败!'); 
                }
            }
            DB::commit();
            return $this->successClient($info, '地址插入成功');
        } catch (\Exception $e) {
            DB::rollBack();
            return $e->getLine().$e->getMessage();
        }
    }

    public function editAddress($info, $isDefault = 0)
    {
        DB::beginTransaction();
        try {
            $addressId = $info['address_id'];
            unset($info['address_id']);
            $back = $this->where('id', $info['id'])->where('user_id', $info['user_id'])->update($info);
            if (!$back) {
                return $this->errorClient($info, '地址更新失败!'); 
            }

            // 如果是取消默认地址 则 进行单独的处理
            if ($isDefault == 0 && $addressId == $info['id']) {
                $user_up = User::where('id', $info['user_id'])->update(['address_id' => 0]);
                if (!$user_up) {
                    return $this->errorClient($info, '默认地址取消失败!'); 
                }
            }
            if ($isDefault == 1 && $addressId != $info['id']) {
                $user_up = User::where('id', $info['user_id'])->update(['address_id' => $info['id']]);
                if (!$user_up) {
                    return $this->errorClient($info, '默认地址更新失败!'); 
                }
            }
            DB::commit();
            return $this->successClient($info, '地址更新成功');
        } catch (\Exception $e) {
            DB::rollBack();
            return $e->getLine().$e->getMessage();
        }
    }
    // 地址ID  和 用户信息( 默认地址ID 和 用户ID )
    public function delAddress($id, $user)
    {
        $data = $this->getAddress($id, $user['id']);
        if (empty($data)) {
            return $this->errorClient($data, '地址信息不存在!'); 
        }
        DB::beginTransaction();
        try {
            if ($data['id'] == $user['address_id']) {
                $default = User::where('id', $user['id'])->update(['address_id' => 0]);
                if (!$default) {
                    return $this->errorClient($data, '当前为默认地址, 默认地址更新失败!'); 
                }
            }
            $del = $this->where('id', $id)->where('user_id', $user['id'])->delete();
            if ($del) {
                DB::commit();
                return $this->successClient($data, '地址删除成功');
            } else {
                return $this->errorClient($data, '地址删除失败!'); 
            }
        } catch (\Exception $e) {
            DB::rollBack();
            return $e->getLine().$e->getMessage();
        }
    }

    // 通过地址ID + 用户ID 获取数据
    public function getAddress($id, $userId = 0)
    {
        return $this->where('id', $id)->where('user_id', $userId)->first();
    }

    // 通过地址ID 获取数据
    public function getAddressId($id)
    {
        return $this->where('id', $id)->first();
    }
    // 地址表字段合法性验证
    private function validate($data)
    {
        $arr = [
            0 => [
                'name' => '收货人名字',
                'value' => $data['accepter_name'],
                'func' => 'is_all_chinese'
            ],
            1 => [
                'name' => '收件人手机',
                'value' => $data['accepter_phone'],
                'func' => 'is_phone'
            ],
            2 => [
                'name' => '详细地址',
                'value' => $data['detail_address'],
                'func' => 'length_limit',
                'min' => 5,
                'max' => 60
            ],
            3 => [
                'name' => '国家码',
                'value' => $data['national_code'],
                'func' => 'length_limit',
                'min' => 6,
                'max' => 6
            ]
        ];

        return ValidateHandler::do($arr);
    }
}
